// 切换视频清晰度代码
import videoJs from "video.js";
import { createRoot } from "react-dom/client";

// 初始化清晰度按钮
const TextTrackMenuItem: any = videoJs.getComponent("TextTrackMenuItem");
const TrackButton: any = videoJs.getComponent("TrackButton");
// var baseComponent = videoJs.getComponent("Component");

const videoQuality = ["超清", "高清", "自动"];

class QualityTrackItem extends TextTrackMenuItem {
  constructor(player: any, options: any) {
    super(player, options);
    this.mount = this.mount.bind(this);
    player.ready(() => {
      this.mount();
    });
    this.on("dispose", () => {
      this.root.unmount();
    });
    if (options.index === 2) {
      this.addClass("vjs-selected");
    }
  }
  // 切换高清播放源，this 指向被点击QualityTrackItem实例
  handleClick(event: any) {
    // 先将所有选项的选中状态设为未选中
    this.parentComponent_.children_.forEach((c: any) => {
      c.selected(false);
    });
    // 选中当前
    this.selected(true);
    // 选中后修改按钮文本
    const btn = document.querySelector(
      ".vjs-menu-button .vjs-icon-placeholder"
    );
    if (!btn) return;
    btn.innerHTML = this.track.label;
    // 其他逻辑 通知修改视频源地址进行切换
    console.log("切换视频源", event);
  }
  mount() {
    this.root = createRoot(this.el()).render(<div>{this.track.label}</div>);
  }
}
class QualityTrackButton extends TrackButton {
  constructor(player: any, options: any) {
    super(player, options);
    this.controlText("画质选择");
    this.children()[0].el().firstElementChild.innerText = "自动";
    this.addClass("vjs-quality");
  }
  createItems() {
    const qualityKeyArray = videoQuality;
    if (qualityKeyArray.length > 0) {
      const result: any = [];
      qualityKeyArray.forEach((key, index: number) => {
        result.push(
          new QualityTrackItem(this.player_, {
            track: {
              label: key,
              value: key,
            },
            selectable: true,
            index,
          })
        );
      });
      return result;
    } else {
      return [];
    }
  }
}

// class QualityTrackButton1 extends TrackButton {
//   constructor(player: any, options: any) {
//     super(player, options);
//     this.on("click", this.clickFunc);
//   }
//   render() {
//     return <div>btn</div>;
//   }
// }

export default QualityTrackButton;
